package com.xiaoyg.producer;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

/**
 * @author xiaoyg
 * @Title: Producer
 * @ProjectName rabbitmq-helloworld
 * @Description: TODO
 * @date 2018/12/316:14
 */
public class Producer {

    //消息队列名称
    private final static String QUEUE_NAME = "helloworld";

    public static void main(String[] args) {

        //创建连接到RabbitMQ
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置RabbitMQ所在主机的IP或者主机名
        connectionFactory.setHost("192.168.8.129");
        //制定用户和密码
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("123456");
        //指定端口
        connectionFactory.setPort(AMQP.PROTOCOL.PORT);
        //创建一个连接
        try {
            Connection connection = connectionFactory.newConnection();
            //创建一个频道
            Channel channel = connection.createChannel();
            //指定一个队列
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);
            //发送一个消息
            String message = "hello world,this a rabbitmq demo";
            //往队列中发出一条消息
            channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
            System.out.println("Send Message: '"+ message+"'");
            //关闭频道和连接
            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
